<template>
  <el-dialog :title="titleMap[mode]" v-model="visible" :width="1500" destroy-on-close :close-on-click-modal="false" :close-on-press-escape="mode != 'show' ? false : true"
             @closed="$emit('closed')" align-center>
    <el-form :model="form" :rules="rules" :disabled="mode=='show'" label-width="130" ref="dialogForm">
      <el-row :gutter="1">
        <el-col :span="8">
          <el-form-item label="组装拆分单编号" prop="code">
            <el-input v-model="form.code" placeholder="组装拆分单编号(不填写自动生成)" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="组装拆分单名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入组装拆分单名称" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="组装拆分单日期" prop="assemble_date">
            <el-date-picker v-model="form.assemble_date" type="date" placeholder="请选择组装拆分单日期" :value-format="'YYYY-MM-DD'" style="width:100%"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="原商品清单" prop="out">
        <div style="display: flex;align-items: center;">
          <el-button type="primary" size="small" icon="el-icon-plus" @click="checkStock" :disabled="!form.out_ware_id">选择商品</el-button>
          <el-form-item label="出库仓库" prop="out_ware_id">
            <el-select v-model="form.out_ware_id" filterable style="width: 200px" placeholder="出库仓库" @change="outChange" clearable>
              <el-option v-for="item in wareList" :key="item.id" :label="item.ware_name" :value="item.id"/>
            </el-select>
          </el-form-item>
        </div>
        <sc-form-table ref="table" v-model="form.out" :addTemplate="addTemplate" placeholder="暂无数据" height="280" hideAdd show-summary>
          <el-table-column label="商品名称" align="center">
            <template #default="scope">
              {{ scope.row.goods_name }}
            </template>
          </el-table-column>
          <el-table-column label="商品编号" align="center">
            <template #default="scope">
              {{ scope.row.goods_code }}
            </template>
          </el-table-column>
			<el-table-column label="商品图片" align="center">
				<template #default="scope">
					<el-image v-if="scope.row.goods_image" style="width: 30px; height: 30px; border-radius: 5px;" :src="scope.row.goods_image" :preview-src-list="[scope.row.goods_image]" preview-teleported="true" hide-on-click-modal align="center"></el-image>
				</template>
			</el-table-column>
          <el-table-column label="商品单位" align="center" prop="unit_name"></el-table-column>
          <el-table-column label="数量" prop="number" align="center">
            <template #default="scope">
              <el-input v-model="scope.row.number" placeholder="数量" @input="totalCompute" @focus="onFocus($event)"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center">
            <template #default="scope">
              <el-input v-model="scope.row.remark" placeholder="备注"></el-input>
            </template>
          </el-table-column>
        </sc-form-table>
      </el-form-item>
      <el-form-item label="新商品清单" prop="enter">
        <div style="display: flex;align-items: center;">
          <el-button type="primary" size="small" icon="el-icon-plus" @click="checkProduct">选择商品</el-button>
          <el-form-item label="入库仓库" prop="in_ware_id">
            <el-select v-model="form.in_ware_id" filterable style="width: 200px" placeholder="入库仓库" @change="inChange" clearable>
              <el-option v-for="item in wareList" :key="item.id" :label="item.ware_name" :value="item.id"/>
            </el-select>
          </el-form-item>
        </div>
        <sc-form-table ref="table" v-model="form.enter" :addTemplate="addTemplate" placeholder="暂无数据" height="280" hideAdd show-summary>
          <el-table-column label="商品名称" align="center">
            <template #default="scope">
              {{ scope.row.goods_name }}
            </template>
          </el-table-column>
          <el-table-column label="商品编号" align="center">
            <template #default="scope">
              {{ scope.row.goods_code }}
            </template>
          </el-table-column>
			<el-table-column label="商品图片" align="center">
				<template #default="scope">
					<el-image v-if="scope.row.goods_image" style="width: 30px; height: 30px; border-radius: 5px;" :src="scope.row.goods_image" :preview-src-list="[scope.row.goods_image]" preview-teleported="true" hide-on-click-modal align="center"></el-image>
				</template>
			</el-table-column>
          <el-table-column label="商品单位" align="center" prop="unit_name"></el-table-column>
          <el-table-column label="数量" prop="number" align="center">
            <template #default="scope">
              <el-input v-model="scope.row.number" placeholder="数量" @input="totalCompute" @focus="onFocus($event)"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center">
            <template #default="scope">
              <el-input v-model="scope.row.remark" placeholder="备注"></el-input>
            </template>
          </el-table-column>
        </sc-form-table>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible=false">取 消</el-button>
      <el-button v-if="mode!='show'" type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
    </template>
  </el-dialog>
  <select-goods v-if="dialog.goods" ref="goodsDialog" @success="goodsUpdate" @closed="dialog.goods=false" :query="{system_disable:0}"></select-goods>
  <select-stock v-if="dialog.select" ref="selectDialog" @success="handleSuccess" @closed="dialog.select=false" :query="{ware_id:form.out_ware_id,allocation:1}"></select-stock>
</template>

<script>
import selectStock from '../stock/selectStock.vue';
import selectGoods from '@/views/goods/info/selectGoods.vue';

export default {
  components: {selectGoods, selectStock},
  emits: ['success', 'closed'],
  data() {
    return {
      mode: "add",
      titleMap: {
        add: '新增',
        edit: '编辑',
        show: '查看',
      },
      visible: false,
      isSaveing: false,
      form: {
        id: "",
        code: "",
        name: "",
        assemble_date: this.moment().format('YYYY-MM-DD'),
        out: [],
        enter: [],
        in_ware_id: "",
        out_ware_id: "",
        remark: "",
      },
      rules: {
        out_ware_id: [
          {required: true, message: '请选择出库仓库'}
        ],
        in_ware_id: [
          {required: true, message: '请选择入库仓库'}
        ],
        name: [
          {required: true, message: '请输入组装拆分单名称'}
        ],
        assemble_date: [
          {required: true, message: '请选择组装拆分单日期'}
        ],
      },
      addTemplate: {},
      dialog: {
        goods: false,
        select: false,
      },
      wareList: [],
    }
  },
  mounted() {
    this.getWare()
  },
  methods: {
    //显示
    open(mode = 'add') {
      this.mode = mode;
      this.visible = true;
      return this
    },
    //表单提交方法
    submit() {
      this.$refs.dialogForm.validate(async (valid) => {
        if (valid) {
          this.isSaveing = true;
          var res = [];
          if (this.form.id) {
            res = await this.$API.procure.zzcx.edit.post(this.form);
          } else {
            res = await this.$API.procure.zzcx.add.post(this.form);
          }
          this.isSaveing = false;
          if (res != '') {
            if (res.code == 1) {
              this.$emit('success', this.form, this.mode)
              this.visible = false;
              this.$message.success("操作成功")
            } else {
              this.$alert(res.message, "提示", {type: 'error'})
            }
          }
        }
      })
    },
    //表单注入数据
    async setData(data) {
      this.form.id = data.id
      var res = await this.$API.procure.zzcx.detail.get({id: data.id});
      this.form.code = res.data.code
      this.form.name = res.data.name
      this.form.assemble_date = res.data.assemble_date
      this.form.out_ware_id = res.data.out[0].ware_id
      this.form.in_ware_id = res.data.enter[0].ware_id
      this.form.remark = res.data.remark
      let out = []
      res.data.out.map(item => {
        out.push({
          id: item.id,
          goods_id: item.goods_id,
          goods_name: item.goods && item.goods.goods_name,
			goods_image: item.goods && item.goods.goods_image,
          unit_name: item.goods.unit && item.goods.unit.unit_name,
          goods_code: item.goods && item.goods.goods_code,
          number: item.number,
          ware_id: item.ware_id,
          remark: item.remark,
        })
      })
      let enter = []
      res.data.enter.map(item => {
        enter.push({
          id: item.id,
          goods_id: item.goods_id,
          goods_name: item.goods && item.goods.goods_name,
			goods_image: item.goods && item.goods.goods_image,
          unit_name: item.goods && item.goods.unit && item.goods.unit.unit_name,
          goods_code: item.goods && item.goods.goods_code,
          number: item.number,
          ware_id: item.ware_id,
          remark: item.remark,
        })
      })
      this.form.out = out
      this.form.enter = enter
    },
    // 选择商品
    checkProduct() {
      this.dialog.goods = true
      this.$nextTick(() => {
        this.$refs.goodsDialog.open('add')
      })
    },
    // 选择商品返回
    goodsUpdate(data) {
      let array = []
      data.map((item) => {
        array.push({
          goods_id: item.id,
          goods_name: item.goods_name,
			goods_image: item.goods_image,
          unit_name: item.unit && item.unit.unit_name,
          mater_code: item.material_code,
          goods_code: item.goods_code,
          ware_id: this.form.in_ware_id ? this.form.in_ware_id : '',
          // price:item.cost_price,
        })
      })
      let existingIds = this.form.enter.map(item => item.goods_id);
      for (let i = array.length - 1; i >= 0; i--) {
        if (existingIds.includes(array[i].goods_id)) {
          array.splice(i, 1);
        }
      }
      this.form.enter = [...this.form.enter, ...array]
    },
    onFocus(event) {
      event.target.select();
    },
    // 获取仓库
    async getWare() {
      var res = await this.$API.goods.ware.all.get();
      this.wareList = res.data;
    },
    /**出库选择商品*/
    checkStock() {
      this.dialog.select = true
      this.$nextTick(() => {
        this.$refs.selectDialog.open('add')
      })
    },
    // 选择商品返回
    handleSuccess(data) {
      let array = []
      data.map((item) => {
        array.push({
          goods_id: item.goods && item.goods.id,
          goods_name: item.goods && item.goods.goods_name,
			goods_image: item.goods && item.goods.goods_image,
          unit_name: item.goods && item.goods.unit && item.goods.unit.unit_name,
          mater_code: item.goods && item.goods.material_code,
          goods_code: item.goods && item.goods.goods_code,
          ware_id: this.form.out_ware_id
        })
      })
      let existingIds = this.form.out.map(item => item.goods_id);
      for (let i = array.length - 1; i >= 0; i--) {
        if (existingIds.includes(array[i].goods_id)) {
          array.splice(i, 1);
        }
      }
      this.form.out = [...this.form.out, ...array]
    },
    outChange() {
      this.form.out = []
    },
    inChange(e) {
      this.form.enter.map(item => item.ware_id = e)
    },
  }
}
</script>

<style>
</style>
